package Panel;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Iterator;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.Border;

import Wyjatki.UnknownButtonException;

public class LibraryPanel {

	private ArrayList<String> ListaSlowek = new ArrayList<String>();
	private Iterator it;
	private String[] Para;
	private int ileDobrze = 0;
	private int ileZle = 0;
	private int ileProb = 0;
	private String setName = "";
	private File f;
	// komponenty
	// panele 2
	JPanel Main = new JPanel();
	JPanel Footer = new JPanel();
	// przyciski
	JButton LoadWords = new JButton("Wczytaj słówka");
	JButton NewSet = new JButton("Nowy zestaw");
	JButton NewWord = new JButton("Nowe słowo");
	JButton SaveWord = new JButton("Zapisz słowo");
	JButton Test = new JButton("Test");
	JButton EndTest = new JButton("Zakończ test");
	// pola tekstowe
	JTextField SetNameField = new JTextField();
	JTextField PolishWordField = new JTextField();
	JTextField EnglishWordField = new JTextField();
	JTextField ResultField = new JTextField();
	// etykiety
	JLabel SetNameLabel = new JLabel("Nazwa zestawu");
	JLabel PolishWordLabel = new JLabel("Słowo polskie");
	JLabel EnglishWordLabel = new JLabel("Słowo angielskie");
	JLabel RightLabel = new JLabel("Prawidłowo");
	JLabel FailureLabel = new JLabel("Błąd");
	JLabel ResultLabel = new JLabel("Wynik");
	JLabel null1 = new JLabel();
	JLabel null2 = new JLabel();
	// checkbox
	JCheckBox RightCB = new JCheckBox("Prawidłowo");
	JCheckBox BadCB = new JCheckBox("Błąd");
	// others
	Border b1 = BorderFactory.createLineBorder(Color.RED);

	public LibraryPanel(JPanel content) {
		// TODO Auto-generated constructor stub

		// elementy inicjujące
		content.removeAll();
		content.setLayout(new BorderLayout());
		// content.setPreferredSize(new Dimension(600, 480));
		// pozycjonujemy Main
		Main.setLayout(new GridLayout(4, 3, 10, 10));
		Main.add(SetNameLabel);
		Main.add(SetNameField);
		Main.add(LoadWords);
		Main.add(null1);
		Main.add(null2);
		Main.add(NewSet);
		Main.add(PolishWordLabel);
		Main.add(PolishWordField);
		Main.add(NewWord);
		Main.add(EnglishWordLabel);
		Main.add(EnglishWordField);
		Main.add(SaveWord);

		// pozycjonujemy Footer
		Footer.setLayout(new GridLayout());
		Footer.add(Test);
		Footer.add(RightCB);
		Footer.add(BadCB);
		Footer.add(ResultLabel);
		Footer.add(ResultField);
		Footer.add(EndTest);
		// dodajemy do okna
		Main.setBorder(b1);
		content.add(Main, BorderLayout.CENTER);
		content.add(Footer, BorderLayout.SOUTH);
		// oprogramowanie akcji kliknięć

		// finalne akcje
		//SetNameField.setEditable(false);
		PolishWordField.setEditable(false);
		ResultField.setEnabled(false);
		ResultField.setPreferredSize(new Dimension(70, 25));
		
		//centrujemy okno
			// rozmiar ekranu	
		Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
		 
			// określamy lokalizację okna
		int w = content.getSize().width;
		int h = content.getSize().height;
		int x = (dim.width-w)/2;
		int y = (dim.height-h)/2;
		
		content.setLocation(x, y);
		

		// dodajemy akcje i listenery
		LoadWords.setActionCommand("loadwords");
		NewSet.setActionCommand("newset");
		NewWord.setActionCommand("newword");
		SaveWord.setActionCommand("saveword");
		Test.setActionCommand("test");
		EndTest.setActionCommand("endtest");
		// listenery
		LoadWords.addActionListener(buttonListener);
		NewSet.addActionListener(buttonListener);
		NewWord.addActionListener(buttonListener);
		SaveWord.addActionListener(buttonListener);
		Test.addActionListener(buttonListener);
		EndTest.addActionListener(buttonListener);
		EnglishWordField.addKeyListener(keyListener);
	}

	KeyListener keyListener = new KeyListener() {

		@Override
		public void keyTyped(KeyEvent arg0) {
			// TODO Auto-generated method stub

		}

		@Override
		public void keyReleased(KeyEvent arg0) {
			// TODO Auto-generated method stub
			if (arg0.getKeyCode() == KeyEvent.VK_ENTER) {
				if (SetNameField.getText() != "") {
					checkAnswer();
					System.out.println("enter pressed");
				}
			}
		}

		@Override
		public void keyPressed(KeyEvent arg0) {
			// TODO Auto-generated method stub

		}
	};

	ActionListener buttonListener = new ActionListener() {

		@Override
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			System.out.println(e.getActionCommand());
			try {
				switch (e.getActionCommand()) {
				case "loadwords":
					JFileChooser fc = new JFileChooser();
					if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
						f = fc.getSelectedFile();
						System.out.println(f);
						LoadWordSet(f);
						// SetNameField.setText(f.toString());
					}
					break;
				case "newset":
					createAndOpenNewWordsSet();
					break;
				case "newword":
					newWord();
					break;
				case "saveword":
					saveWord();
					break;
				case "endtest":
					endTest();
					break;
				case "test":
					startTest();
					break;
				default:
					throw new UnknownButtonException();
				}
			} catch (Exception ex) {
				System.out.println(ex);
			}
		}
	};

	private void LoadWordSet(File f) {
		ListaSlowek.clear();
		RandomAccessFile plik;
		try {
			plik = new RandomAccessFile(f, "r");
			String linia = "";
			linia = plik.readLine();
			setName = linia;
			while ((linia = plik.readLine()) != null) {
				ListaSlowek.add(linia);
			}
			plik.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("Liczba par slowek: " + ListaSlowek.size());
		SetNameField.setText(setName);
	}

	private void setNextWordsPair() {
		if (it.hasNext()) {
			String temp = (String) it.next();
			Para = temp.split(" ");
			PolishWordField.setText(Para[0] + ", " + Para[1]);
			EnglishWordField.setText("");
		} else {
			endTest();
		}
	}

	private void checkAnswer() {
		System.out.println(EnglishWordField.getText() + " " + Para[1]);
		ileProb++;
		if (EnglishWordField.getText().equals(Para[1])) {
			ileDobrze++;
			setNextWordsPair();
			RightCB.setSelected(true);
			BadCB.setSelected(false);
		} else {
			ileZle++;
			RightCB.setSelected(false);
			BadCB.setSelected(true);
		}
		
		
	}

	private void startTest(){
		it = ListaSlowek.iterator();
		ileDobrze = 0;
		ileProb = 0;
		ileZle = 0;
		setNextWordsPair();
	}
	
	private void endTest() {
		System.out.println("Dobrze/ogolem: " + ileDobrze + "/" + ileProb);
		int wynik = (int) (((double) ileDobrze / ileProb)*100);
		JOptionPane.showMessageDialog(new JFrame("message"), "Test został zakończony. Twój wynik: \n" + ileDobrze + "/" + ileProb +" = "+wynik+"%");
		ResultField.setText(wynik + "%");
		it = ListaSlowek.iterator();
		PolishWordField.setText(null);
		EnglishWordField.setText(null);
		ileDobrze = 0;
		ileZle = 0;
		ileProb = 0;
	}
	
	private void newWord(){
		endTest();
		PolishWordField.setEditable(true);
	}
	
	private void saveWord(){
		try {
			RandomAccessFile plik = new RandomAccessFile(f, "rw");
			plik.seek(plik.length());
			plik.writeBytes("\n" +PolishWordField.getText() + " " + EnglishWordField.getText());
			plik.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ListaSlowek.add(PolishWordField.getText() + " " + EnglishWordField.getText());
		PolishWordField.setEditable(false);
		//LoadWordSet(f);
	}
	
	private void createAndOpenNewWordsSet(){
		JFileChooser fc = new JFileChooser();
		if (fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
			f = fc.getSelectedFile();
			System.out.println(f);
			RandomAccessFile plik;
			try {
				plik = new RandomAccessFile(f, "rw");
				plik.writeBytes(SetNameField.getText());
				plik.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 			
			//LoadWordSet(f);
			// SetNameField.setText(f.toString());
		}
	}
	
}
